<template>
  <view>
	<view class="s_money">
	  <view class="title">消费门店</view>
	  <view class="tisp">请输入选择消费的门店</view>
	  <view class="ipnut_view">
		<lin-select
		:list="productList2"
		:loading="loading"
		loading-text="数据加载中"
		value-key="id"
		name-key="name"
		max-height="180"
		placeholder="选择门店名称"
		@input="input2"
		v-model="mytext2"
		@confirm="confirm"
	  /> 
	  </view>
	</view>
    <view class="content">
      <view class="title">拍小票</view>
      <view class="tisp">包含清晰的店铺、时间、交易号、消费金额</view>
	  <view class="guide" @click="()=> show = true">小票上传指南</view>
      <view class="uolds" @click="UopLdo()" :class="{ disabled: isLoading }">
        <view class="uolod_icon">
          <image src="https://img.shihhl.com/shequ/ps.png" mode="widthFix"></image>
        </view>
        <!-- 加载状态提示 -->
        <view class="loading-mask" v-if="isLoading">
          <view class="loading-text">上传中 {{uploadProgress}}%</view>
        </view>
      </view>
      <view class="u_imglist">
        <view class="u_img" v-for="(item, index) in vimages" :key="index" @click="PreviewImage(index)">
          <image :src="item" mode=""></image>
          <image src="/static/de.png" mode="widthFix" class="del" @click.stop="deleteImage(index)"></image>
        </view>
        <!-- 显示已选图片数量/最大数量 -->
   <!--     <view class="image-count" v-if="vimages.length > 0">
          {{vimages.length}}/6 张图片
        </view> -->
      </view>
    </view>
    <view class="s_money">
      <view class="title">消费金额</view>
      <view class="tisp">小票审核时间为1-3个工作日审核通过后积分到账。</view>
      <view class="ipnut_view">
	    <input 
	      type="digit" 
	      placeholder="请输入消费金额" 
	      v-model="totalAmount"
	      @input="handleAmountInput"
	      maxlength="10"
	    />
		</view>
    </view>
    <view class="btn" @click="submitForm" :class="{ disabled: isLoading || !validateForm() }">
      {{ isLoading ? '上传中...' : '提交上传' }}
    </view>
		<u-popup v-model="show" mode="center" :border-radius="20" :safe-area-inset-bottom="false">
			<view class="pupcenter">
				<view class="title">上传小票指南</view>
				<!-- 只让中间文本区域滚动 -->
				<scroll-view 
					class="popup-content-scroll" 
					scroll-y 
					enhanced 
					show-scrollbar
					:scroll-with-animation="false"
				>
					<view class="puptext">
						亲爱的会员朋友，感谢您使用松江大橘邻里小程序自助积分功能。通过上传消费小票，您可以轻松累积积分兑换福利。请按以下步骤操作：
						<br/>
						<text style="font-weight: 600;">1. 拍摄小票</text>
					       <br/>确保小票清晰完整，所有消费内容、金额、门店名称及消费日期需清晰可见。<br/>
					   建议在光线充足的环境下拍摄，避免反光、折叠或模糊。<br/>
						<text style="font-weight: 600;">2. 进入上传页面</text><br/>
					打开小程序，点击【自助积分】→【拍小票】。<br/>
					允许小程序访问相机权限，直接拍摄或从相册选择已保存的小票照片。<br/>
						<text style="font-weight: 600;">3. 填写消费信息</text><br/>
					消费门店：输入消费门店的关键字，并从自动推荐关联的菜单中找到您消费的具体门店。<br/>
					消费金额：手动填写小票上的实际支付金额（注意：积分按实际支付金额计算）。<br/>
					<text style="font-weight: 600;">4. 提交审核</text><br/>
					确认信息无误后，点击【提交上传】。<br/>
					系统将在1-3个工作日内审核完成，审核通过后积分自动到账，您可在【会员】→【我的积分】中查看。<br/>
					<text style="font-weight: 600;">注意事项</text><br/>
					仅限松江大橘邻里门店消费小票，其他商户小票无效。<br/>
					每张小票仅可上传一次，重复上传无效。<br/>
					如小票信息不全、涂改或过期（超过7天），可能导致审核失败。<br/>
					如有问题，请联系客服微信/电话：13621636879，我们将竭诚为您服务！
					</view>
				</scroll-view>
				<view class="mygodd" @click="()=> show = false">
					我知道了
				</view>
			</view>
		</u-popup>
		<u-popup v-model="show1" mode="center" :border-radius="20">
			<view class="pupcenter">
				<view class="title">请选择消费门店</view>
				<view class="p_cont">
					<view class="te">选门店</view>
					<view style="font-size: 26rpx;color: #666666;margin-bottom: 30rpx;">请您下拉或输入您消费的门店</view>
					<view class="inpst">
						<image src="/static/home/t1.png" mode="widthFix"></image>
				  <lin-select
						    :list="productList2"
						    :loading="loading"
						    loading-text="数据加载中"
						    value-key="id"
						    name-key="name"
						    max-height="180"
						    placeholder="选择门店名称"
						    @input="input2"
						    v-model="mytext2"
							@confirm="confirm"
						  /> 
					</view>
				</view>
				<view class="mygodd" @click="PuCofing">
					确认
				</view>
			</view>
		</u-popup>
  </view>
</template>

<script>
import { receipt , shoppage } from '@/core/api/index.js'
export default {
  data() {
    return {
      vimages: [],
      isLoading: false,
      uploadProgress: 0,
      totalAmount: '',
      uploadQueue: 0, // 待上传的图片队列数量
      uploadedCount: 0, // 已上传的图片数量
	  show: false,
	  show1: false,
	  loading: false,
	  shopId: '',
	  mytext2: '',
	  productList2: []
    }
  },
  methods: {
	  PuCofing() {
		  if(this.shopId === ''){
		  	uni.showToast({
		  		title: '请选择门店',
				icon: 'none'
		  	})
		  	return
		  }
		  this.show1 = false
		  this.submitForm()
	  },
	  
	  // 远程加载门店数据
	 async input2(val) {
		let prems = {
			condition: {
				name: val
			}
		}
		this.loading = true
		try {
			const { data }  = await shoppage(prems)
			this.productList2 = data.records || []
			// 无匹配结果时提示
			if (this.productList2.length === 0) {
				uni.showToast({
					title: '未找到匹配的门店',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('加载门店失败:', error)
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			})
			this.productList2 = []
		} finally {
			this.loading = false
		}
	  },
	  
	  confirm(e) {
		  console.log(e,'打印')
		this.shopId = e
	},
	  
    // 预览图片
    PreviewImage(index) {
      uni.previewImage({
        urls: this.vimages,
        current: index,
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
          success: function(data) {
            console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
          },
          fail: function(err) {
            console.log(err.errMsg);
          }
        }
      });
    },
    
    // 删除图片
    deleteImage(index) {
      this.vimages.splice(index, 1);
    },
    
    // 选择并上传图片
    UopLdo() {
      // 如果正在加载中，则不执行操作
      if (this.isLoading) return;
      
      uni.chooseImage({
        count: 6 - this.vimages.length, // 最多选择6张，减去已选的数量
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'], // 允许从相册和相机选择
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          if (tempFilePaths.length === 0) return;
          
          this.isLoading = true;
          this.uploadQueue = tempFilePaths.length;
          this.uploadedCount = 0;
          this.uploadProgress = 0;
          
          // 多张图片上传
          tempFilePaths.forEach((resimg) => {
            this.uploadImage(resimg);
          });
        }
      });
    },
    
    // 上传单张图片
    uploadImage(filePath) {
      uni.uploadFile({
        url: 'https://shequ.shihongkeji.cn' + '/webapi/file/upload',
        filePath: filePath,
        name: "file",
        header: {
          'token': uni.getStorageSync('token')
        },
        success: (uploadFileRes) => {
          try {
            let uplodata = JSON.parse(uploadFileRes.data);
            if (uplodata.code === '00000') {
              this.vimages.push('https:' + uplodata.result.filePath);
            } else {
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            console.error('解析上传结果失败:', e);
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        },
        fail: (uploadFileErr) => {
          console.error('upload fail:', uploadFileErr);
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          // 无论成功或失败，都算完成一张
          this.uploadedCount++;
          this.updateProgress();
          
          // 所有图片上传完成
          if (this.uploadedCount === this.uploadQueue) {
            setTimeout(() => {
              this.isLoading = false;
              // 计算成功上传的数量
              const successCount = this.vimages.length - (this.vimages.length - this.uploadedCount);
              uni.showToast({
                title: `成功上传${successCount}张图片`,
                icon: 'success'
              });
            }, 300);
          }
        }
      });
    },
    
    // 更新上传进度
    updateProgress() {
      this.uploadProgress = Math.round((this.uploadedCount / this.uploadQueue) * 100);
    },
    
    // 处理金额输入
    handleAmountInput(e) {
      // 限制为最多两位小数的数字
      this.totalAmount = e.detail.value
        .replace(/[^\d.]/g, '')         // 清除非数字和点以外的字符
        .replace(/^\./g, '')            // 清除开头的点
        .replace(/\.{2,}/g, '.')        // 只保留一个点
        .replace('.', '$#$')            // 临时替换点
        .replace(/\./g, '')             // 清除其他点
        .replace('$#$', '.')            // 恢复点
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 限制两位小数
    },
    
    // 验证表单
    validateForm() {
      return this.vimages.length > 0 
        && this.totalAmount 
        && parseFloat(this.totalAmount) > 0 
        && this.shopId;
    },
    
    // 提交表单
    async submitForm() {
      if (this.isLoading) return;
      
      if (!this.validateForm()) {
        if (!this.shopId) {
          this.show1 = true;
        } else {
          uni.showToast({
            title: '请上传图片并输入正确的消费金额',
            icon: 'none'
          });
        }
        return;
      }
      
      this.isLoading = true;
      uni.showLoading({
        title: '提交中...'
      });
      
      try {
        const parmes = {
          picUrls: this.vimages,
          amount: this.totalAmount,
          shopId: this.shopId
        };
        
        const data = await receipt(parmes);
        
        if (data.code === '00000') {
          uni.hideLoading();
          uni.navigateTo({
            url: '/pages/receipt/success'
          });
          uni.showToast({
            title: '提交成功，等待审核',
            icon: 'none'
          });
          
          // 重置表单
          this.vimages = [];
          this.totalAmount = '';
          this.shopId = '';
          this.mytext2 = '';
        } else {
          uni.hideLoading();
          uni.showToast({
            title: data.msg || '提交失败，请重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交表单失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

<style>
page{
  background: url('https://img.shihhl.com/shequ/bk.png') no-repeat;
  background-size: 100%;
  min-height: 100vh;
}
</style>

<style lang="scss">
.content{
  width: 91%;
  background-color: #fff;
  padding: 72rpx 36rpx 30rpx;
  margin: 30rpx auto 20rpx;
  border-radius: 20rpx;
  position: relative;
  
  .guide{
	  background: linear-gradient(90deg, #FF4E36 0.19%, #FF2976 101.22%);
	  width: 170rpx;
	  height: 60rpx;
	  text-align: center;
	  line-height: 60rpx;
	  color: #fff;
	  border-radius: 40rpx 0px 0px 40rpx;
	  font-size: 24rpx;
	  position: absolute;
	  right: 0%;
	  top: 6%;
  }
  
  .title{
    font-size: 34rpx;
    font-weight: 600;		  
  }
  
  .tisp{
    font-size: 24rpx;
    color: #666;
    margin-top: 10rpx;
  }
  
  .uolds{
    height: 350rpx;
    margin: 20rpx auto;
    background-color: #000;
    position: relative;
    overflow: hidden;
    border-radius: 10rpx;
    
    &.disabled {
      opacity: 0.7;
      pointer-events: none;
    }
  }
  
  .uolod_icon{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100rpx;
    transform: translate(-50%, -50%);
    
    image{
      width: 100rpx;
      height: auto;
    }
  }
  
  .loading-mask{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    
    .loading-text{
      color: white;
      font-size: 32rpx;
    }
  }
}

.s_money{
  width: 91%;
  background-color: #fff;
  padding: 32rpx 36rpx;
  margin: 20rpx auto 20rpx;
  border-radius: 20rpx;
  
  .title{
    font-size: 34rpx;
    font-weight: 600;		  
  }
  
  .tisp{
    font-size: 26rpx;
    color: #666;
    margin-top: 10rpx;
  }
  
  .ipnut_view{
    border-radius: 12rpx;
    border: 1px solid #F6F6F6;
    background: #F3F3F4;
    height: 88rpx;
    padding-left: 30rpx;
    margin-top: 20rpx;
    
    input{
      width: 100%;
      height: 100%;
      font-size: 30rpx;
    }
  }
}

.btn{
  width: 91%;
  margin: 30rpx auto 50rpx;
  font-size: 30rpx;
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #F26B2E;
  border-radius: 40rpx;
  color: #fff;
  transition: all 0.3s;
  
  &.disabled{
    background-color: #ccc;
    pointer-events: none;
  }
}

.u_imglist{
  display: flex;
  flex-wrap: wrap;
  margin-top: 0rpx;
  
  .u_img{
    width: 100rpx;
    height: 100rpx;
    margin-left: 20rpx;
    margin-top: 20rpx;
    position: relative;
    border-radius: 8rpx;
    // overflow: hidden;
    
    image{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .del{
      width: 35rpx;
      height: auto;
      position: absolute;
      right: -14%;
      top: -8%;
      cursor: pointer;
      background-color: #fff;
      border-radius: 50%;
      padding: 2rpx;
    }
  }
  
  .image-count{
    margin-left: 20rpx;
    margin-top: 15rpx;
    font-size: 24rpx;
    color: #666;
  }
}

.pupcenter{
  width: 85vw;
  background-color: #fff;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  
  .title{
    height: 108rpx;
    text-align: center;
    color: #fff;
    line-height: 108rpx;
    font-size: 30rpx;
    background-color: #FF3168;
    border-radius: 20rpx 20rpx 0 0;
    /* 标题固定在顶部不滚动 */
    flex-shrink: 0;
  }
  
  /* 中间内容滚动区域 */
  .popup-content-scroll {
    /* 动态计算高度：弹窗总高度 - 标题高度 - 按钮高度 */
    height: calc(90vh - 108rpx - 90rpx - 80rpx);
    width: 100%;
    flex-shrink: 1;
    overflow: hidden;
    -webkit-overflow-scrolling: touch; /* 关键属性，确保iOS设备正常滚动 */
  }
  
  .puptext{
    padding: 30rpx 40rpx;
    line-height: 50rpx;
    width: 100%;
    box-sizing: border-box;
  }
  
  .mygodd{
    background-color: #F26B2E;
    border-radius: 60rpx;
    height: 90rpx;
    text-align: center;
    color: #fff;
    line-height: 90rpx;
    width: 70%;
    margin: 30rpx auto 40rpx;
    /* 按钮固定在底部不滚动 */
    flex-shrink: 0;
  }
}
</style>
